package com.hxh.learn.config;

import cn.hutool.json.JSONUtil;
import com.hxh.common.unification.ResultOutcome;
import com.hxh.common.utils.JwtUtil;
import com.hxh.learn.model.SysUser;
import com.hxh.learn.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author: hxh
 * @Date: 2023/3/3
 */
@Component
public class LoinSuccessHandle implements AuthenticationSuccessHandler {
    @Autowired
    private ISysUserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //设置返回json
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ServletOutputStream stream = httpServletResponse.getOutputStream();
        SysUser user = userService.getByName(authentication.getName());
        String token = JwtUtil.getJwtToken(user.getUserId(), user.getUsername());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("Authorization",token);
        ResultOutcome<HashMap<String, Object>> result = ResultOutcome.successResult(hashMap);

        stream.write(JSONUtil.toJsonStr(result).getBytes());
        stream.flush();
        stream.close();

    }
}
